#coding=utf-8
#author:yangyongzhen
#QQ:534117529
#'CardTest TcpServer  - Simple Test Card Tool 1.00' 

import sys,threading,time;
import serial;
import binascii,encodings;
import re;
import os;
from socket import *
from struct import *;
#from myutil import *;
#name: myutil.py

mylock = threading.RLock() 

def print_hex1(s,prev='0x'):
    for c in s:
        print '%s%02x' %(prev,ord(c)),
    print
def print_hex(s):
    for c in s:
    	print '%02x' %(ord(c)),
    print

def hexto_str(s):
	r =''
	for c in s:
		r += '%02x' %(ord(c))
	return r
def strto_hex(s):
	r = s.decode('hex')
	return r
#''代表服务器为localhost

#在一个非保留端口号上进行监听


class ComThread:
    def __init__(self, Port=0):
        self.l_serial = None;
        self.alive = False;
        self.waitEnd = None;
        self.port = Port;

        #TCP部分
        self.myHost = ''
        self.myPort = 5050
        self.sockobj = socket(AF_INET, SOCK_STREAM)
        self.connection = None
        #数据
        self.snddata = ''
        self.rcvdata = ''

    def waiting(self):
        if not self.waitEnd is None:
            self.waitEnd.wait();


    def SetStopEvent(self):
        if not self.waitEnd is None:
            self.waitEnd.set();
        self.alive = False;
        self.stop();


    def start(self):
        self.l_serial = serial.Serial();
        self.l_serial.port = self.port;
        self.l_serial.baudrate = 115200;
        self.l_serial.timeout = 2;  #秒
        self.l_serial.open();

        if self.l_serial.isOpen():
            self.waitEnd = threading.Event();
            self.alive = True;
            print 'open serial port %d ok!\n' %(self.port+1)
            print 'baudrate:115200 \n'
            self.thread_read = None;
            self.thread_read = threading.Thread(target=self.FirstReader);
            self.thread_read.setDaemon(1);
            self.thread_read.start();

            self.thread_write = None;
            self.thread_write = threading.Thread(target=self.FirstWriter);
            self.thread_write.setDaemon(1);
            self.thread_write.start();

            #TCP部分
            self.thread_TcpServer = None;
            self.thread_TcpServer = threading.Thread(target=self.TcpServer);
            self.thread_TcpServer.setDaemon(1);
            self.thread_TcpServer.start();

            self.thread_TcpSend = None;
            self.thread_TcpSend = threading.Thread(target=self.TcpSend);
            self.thread_TcpSend.setDaemon(1);
            self.thread_TcpSend.start();

            return True;
        else:
            return False;


    def FirstReader(self):
        while self.alive:
            # 接收间隔
            time.sleep(0.1);
            try:
                data = '';
                n = self.l_serial.inWaiting();
                if n:
                    data = data+self.l_serial.read(n);
                    #for l in xrange(len(data)):
                        #print '%02X' % ord(data[l]),
                    # 发送数据
                    print 'serial recv:'
                    print data;
                    mylock.acquire() 
                    self.snddata = data
                    mylock.release()
                    #print_hex(data);
                
                    
                # 判断结束
               
            except Exception, ex:
                print str(ex);

        self.waitEnd.set();
        self.alive = False;

    def FirstWriter(self):
        while self.alive:
            # 接收间隔
            time.sleep(0.1);
            try:
                #snddata = raw_input('\nenter data send:\n')
                if self.rcvdata!='':
                    self.l_serial.write(self.rcvdata); 
                    print 'serial send:'
                    print self.rcvdata;
                    mylock.acquire() 
                    self.rcvdata = '';
                    mylock.release()
                #print_hex(snddata);
                
            except Exception, ex:
                print str(ex);
        self.waitEnd.set();
        self.alive = False;

    def TcpServer(self):
    	self.sockobj.bind((self.myHost, self.myPort))
        self.sockobj.listen(1)
        print 'TcpServer listen at 5050 oK!\n'
        print 'Waiting for connect...\n'
        while True:
            # 接收间隔
            time.sleep(0.1);
            self.connection, address = self.sockobj.accept()
            print 'Server connected by', address
            self.snddata = ''
            self.rcvdata = ''
            while True:
		        #读取客户端套接字的下一行
		        data = self.connection.recv(1024)
		        #如果没有数量的话，那么跳出循环
		        if not data: break
		        #发送一个回复至客户端
		        mylock.acquire() 
		        self.snddata = ''
		        self.rcvdata = data
		        mylock.release()
		        #connection.send('Echo=>' + data)
            self.connection.close()

        self.waitEnd.set();
        self.alive = False;

    def TcpSend(self):
        while True:
            # 接收间隔
            time.sleep(0.1);
            while True:
	            time.sleep(0.1);
	            try:
	            	if not self.connection is None:
	            		if self.snddata != '':
	            			self.connection.send(self.snddata)
	            			mylock.acquire() 
	            			self.rcvdata = ''
	            			self.snddata = ''
	            			mylock.release()
	            except Exception, ex:
			    	pass    		
    def stop(self):
        self.alive = False;
        self.thread_read.join();
        if self.l_serial.isOpen():
            self.l_serial.close();



#测试用部分
if __name__ == '__main__':
    print 'CardTest TcpServer  - Simple Test Card Tool 1.00\n' 
    print 'Author:yangyongzhen\n'
    print 'QQ:534117529\n'
    print 'Copyright (c) Newcapec 2015-2016.\n'

    com =raw_input('please enter com port(1-9):')
    rt = ComThread(int(com)-1);
    try:
        if rt.start():
            rt.waiting();
            rt.stop();
        else:
            pass;            
    except Exception,se:
        print str(se);

    if rt.alive:
        rt.stop();
    os.system("pause")

    print '';
    print 'End OK .';
    del rt;